package com.nebula.service.Impl;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.nebula.common.ServerResponse;
import com.nebula.mapper.FilesMapper;
import com.nebula.mapper.FoldersMapper;
import com.nebula.pojo.Files;
import com.nebula.pojo.Folders;
import com.nebula.pojo.User;
import com.nebula.service.IFileUploadService;
import com.nebula.service.IFolderService;
import com.nebula.util.IDUtil;
import com.nebula.vo.DirectoryVo;

import net.sf.json.JSONArray;

@Service("folderService")
public class FolderServiceImpl implements IFolderService {
	
	private Logger logger = LoggerFactory.getLogger(FolderServiceImpl.class);
	
	@Autowired
	private FoldersMapper foldersMapper;
	@Autowired
	private FilesMapper filesMapper;
	@Autowired
	private IFileUploadService fileUploadService;
	
	public ServerResponse saveOrUpdateFolder(Folders folders){
		if(folders != null){
			if(folders.getFolderid() != null){
				int rowCount = foldersMapper.updateByPrimaryKeySelective(getNewFolder(folders));
				if(rowCount > 0){
					return ServerResponse.createBySuccessMessage("修改文件夹名成功");
				}
				return ServerResponse.createBySuccessMessage("修改文件夹名失败");
			}else{
				folders.setInRecycle(1);
				int rowCount = foldersMapper.insert(getNewFolder(folders));
				if(rowCount > 0){
					return ServerResponse.createBySuccessMessage("创建文件夹成功");
				}
				return ServerResponse.createBySuccessMessage("创建文件夹失败");
			}
		}
		return ServerResponse.createByErrorMessage("创建或更新文件夹参数不正确");
	}
	
	public int getAllFilesIdByUsername(String username){
		return foldersMapper.selectAllFileFolderIdByUsername(username);
	}
	
	public Folders getFolderNameByFolderId(int folderId){
		return foldersMapper.selectByPrimaryKey(folderId);
	}
	
	public JSONArray getChildrenParallelFolder(Integer folderId,User user){
		List<Folders> folderList = foldersMapper.selectFolderChildrenByParentId(folderId,user.getUsername());
		if(CollectionUtils.isEmpty(folderList)){
			logger.info("未找到当前目录的子目录");
		}
		List<DirectoryVo> directoryVos = Lists.newArrayList();
		for(Folders folders : folderList){
			DirectoryVo directoryVo = assembleDirectoryVo(folders,user);
			directoryVos.add(directoryVo);
		}
		JSONArray resultJson = JSONArray.fromObject(directoryVos);
		return resultJson;
	}
	
	public ServerResponse<List<Integer>> selectFoldersAndChildrenById(Integer folderId,User user){
		Set<Folders> foldersSet = Sets.newHashSet();
		findChildFolders(foldersSet, folderId,user);
		
		List<Integer> folderIdList = Lists.newArrayList();
		if(folderId != null){
			for(Folders foldersItem : foldersSet){
				folderIdList.add(foldersItem.getFolderid());
			}
		}
		return ServerResponse.createBySuccess(folderIdList);
	}
	
	public ServerResponse<String> plDel(String groupId,User user){
		String []str = groupId.split(",");
		Map<String, List<Long>> fileIdMap = Maps.newHashMap();
		List<Long> fileIdList = Lists.newArrayList();
		
		Map<String, List<Integer>> folderIdMap = Maps.newHashMap();
		List<Integer> folderIdList = Lists.newArrayList();
		
		for(int i = 0,len = str.length;i < len;i++){
			if(str[i].length() <= 11){
				Set<Folders> folderSet = Sets.newHashSet();
				findChildFolders(folderSet, Integer.parseInt(str[i]),user);
				for(Folders folders : folderSet){
					folderIdList.add(folders.getFolderid());
				}
			}else{
				fileIdList.add(Long.parseLong(str[i]));
			}
		}
		
		List<Long> fileIdList2 = Lists.newArrayList();
		if(CollectionUtils.isNotEmpty(folderIdList)){
			folderIdMap.put("folderid", folderIdList);
			fileIdList2 = filesMapper.selectFileIdByFodlerId(user.getUsername(), folderIdMap);
		}
		if(CollectionUtils.isNotEmpty(fileIdList2) && CollectionUtils.isNotEmpty(fileIdList)){
			fileIdList.addAll(fileIdList2);
			fileIdMap.put("fileid", fileIdList);
		}else if(CollectionUtils.isNotEmpty(fileIdList2) && CollectionUtils.isEmpty(fileIdList)){
			fileIdMap.put("fileid", fileIdList2);
		}else if(CollectionUtils.isEmpty(fileIdList2) && CollectionUtils.isNotEmpty(fileIdList)){
			fileIdMap.put("fileid", fileIdList);
		}
		
		int resultCount = 0;
		if(fileIdMap.isEmpty() && !folderIdMap.isEmpty()){
			resultCount = foldersMapper.plDelete(folderIdMap, user.getUsername());
			if(resultCount > 0){
				return ServerResponse.createBySuccessMessage("删除成功");
			}
		}else if(!fileIdMap.isEmpty()){
			resultCount = filesMapper.plDelete(fileIdMap,user.getUsername());
			if(resultCount > 0){
				if(folderIdMap.isEmpty()){
					return ServerResponse.createBySuccessMessage("删除成功");
				}else{
					resultCount = foldersMapper.plDelete(folderIdMap, user.getUsername());
					if(resultCount > 0){
						return ServerResponse.createBySuccessMessage("删除成功");
					}
				}
			}
		}
		return ServerResponse.createByErrorMessage("删除失败");
	}
	
	//复制到
	public ServerResponse<String> copyTo(Integer folderid,String valArr,User user){
		String []str = valArr.split(",");
		
		List<Folders> folderList = Lists.newArrayList();
		List<Files> fileList = Lists.newArrayList();
		
		for(int i = 0,len = str.length;i < len ; i++){
			if(str[i].length() <= 11){
				int parentid = foldersMapper.selectParentIdByFolderId(Integer.parseInt(str[i]));
				Set<Folders> folderSet = Sets.newHashSet();
				findChildFolders(folderSet, Integer.parseInt(str[i]),user);
				for(Folders foldersItem : folderSet){
					if(foldersItem.getFolderid().equals(folderid) || folderid.equals(parentid)){
						return ServerResponse.createByErrorMessage("不能将文件复制到自身或其子目录下");
					}
				}
				//要复制的文件夹根目录
				Folders folders = foldersMapper.selectByPrimaryKey(Integer.parseInt(str[i]));
				folders.setParentid(folderid);
				folders.setUsername(user.getUsername());
				folders.setFolderName(getNewFolder(folders).getFolderName());
				folderList.add(folders);
			}else{
				int folderId = filesMapper.selectFolderIdByFileId(Long.parseLong(str[i]));
				if(folderId == folderid){
					return ServerResponse.createByErrorMessage("不能将文件复制到自身或其子目录下");
				}else{
					Files files = filesMapper.selectByPrimaryKey(Long.parseLong(str[i]));
					files.setFolderId(folderid);
					files.setFileid(IDUtil.getItemId());
					files.setUsername(user.getUsername());
					files.setFileRealName(fileUploadService.setNewFileName(files));
					fileList.add(files);
				}
			}
		}
		
		if(CollectionUtils.isNotEmpty(folderList) && CollectionUtils.isNotEmpty(fileList)){
			int resultCount = filesMapper.plInsert(fileList);
			if(resultCount > 0){
				if(recursiveInsert(folderList,user)){
					return ServerResponse.createBySuccessMessage("文件复制成功");
				}else{
					return ServerResponse.createBySuccessMessage("部分文件复制成功(文件夹复制失败)");
				}
			}
			return ServerResponse.createByErrorMessage("文件复制失败");
		}else if(CollectionUtils.isNotEmpty(folderList) && CollectionUtils.isEmpty(fileList)){
			if(recursiveInsert(folderList,user)){
				return ServerResponse.createBySuccessMessage("文件复制成功");
			}
			return ServerResponse.createByErrorMessage("文件复制失败");
		}else if(CollectionUtils.isEmpty(folderList) && CollectionUtils.isNotEmpty(fileList)){
			int resultCount = filesMapper.plInsert(fileList);
			if(resultCount > 0){
				return ServerResponse.createBySuccessMessage("文件复制成功");
			}
			return ServerResponse.createByErrorMessage("文件复制失败");
		}else{
			return ServerResponse.createByErrorMessage("参数错误");
		}
	}
	
	//移动到
	public ServerResponse<String> moveTo(Integer folderid,String valArr,User user){
		ServerResponse<String> responseServer = copyTo(folderid, valArr,user);
		if(responseServer.isSuccess()){
			responseServer = plDel(valArr, user);
			if(responseServer.isSuccess()){
				return ServerResponse.createBySuccessMessage("文件移动成功");
			}else 
				return ServerResponse.createBySuccessMessage("文件移动成功，删除原文件失败");
		}
		return ServerResponse.createByErrorMessage("不能将文件移动到自身或其子目录下");
	}
	
	//收藏文件
	public ServerResponse<String> saveTo(Integer folderid,String valArr,User user){
		String []str = valArr.split(",");
		long size = 0;
		
		List<Folders> folderList = Lists.newArrayList();
		List<Files> fileList = Lists.newArrayList();
		for(int i = 0,len = str.length;i < len;i++){
			if(str[i].length() <= 11){
				//要复制的文件夹根目录
				Folders folders = foldersMapper.selectByPrimaryKey(Integer.parseInt(str[i]));
				folders.setParentid(folderid);
				folders.setUsername(user.getUsername());
				folders.setFolderName(getNewFolder(folders).getFolderName());
				folderList.add(folders);
			}else{
				Files files = filesMapper.selectByPrimaryKey(Long.parseLong(str[i]));
				files.setFolderId(folderid);
				files.setFileid(IDUtil.getItemId());
				files.setUsername(user.getUsername());
				files.setFileRealName(fileUploadService.setNewFileName(files));
				size += files.getFileSize();
				fileList.add(files);
			}
		}
		
		if(CollectionUtils.isNotEmpty(folderList) && CollectionUtils.isNotEmpty(fileList)){
			if(user.getUsedStorageSpace() + size > user.getUserGroups().getMaxStorageSpace()){
				return ServerResponse.createByErrorMessage("空间不足，请购买");
			}
			
			int resultCount = filesMapper.plInsert(fileList);
			if(resultCount > 0){
				if(recursiveInsert(folderList,user)){
					
					return ServerResponse.createBySuccessMessage("保存文件到私有云成功");
				}else{
					return ServerResponse.createBySuccessMessage("部分文件保存到私有云成功(文件夹复制失败)");
				}
			}
			return ServerResponse.createByErrorMessage("保存文件到私有云失败");
		}else if(CollectionUtils.isNotEmpty(folderList) && CollectionUtils.isEmpty(fileList)){
			if(recursiveInsert(folderList,user)){
				return ServerResponse.createBySuccessMessage("保存文件到私有云成功");
			}
			return ServerResponse.createByErrorMessage("保存文件到私有云失败");
		}else if(CollectionUtils.isEmpty(folderList) && CollectionUtils.isNotEmpty(fileList)){
			if(user.getUsedStorageSpace() + size > user.getUserGroups().getMaxStorageSpace()){
				return ServerResponse.createByErrorMessage("空间不足，请购买");
			}
			
			int resultCount = filesMapper.plInsert(fileList);
			if(resultCount > 0){
				return ServerResponse.createBySuccessMessage("保存文件到私有云成功");
			}
			return ServerResponse.createByErrorMessage("保存文件到私有云失败");
		}else{
			return ServerResponse.createByErrorMessage("参数错误");
		}
	}
	
	public int getFolderCount(Integer folderid){
		int resultCount = foldersMapper.selectFolderCountByPrimaryKey(folderid);
		if(resultCount > 0){
			return resultCount;
		}
		return 0;
	}
	
	private Folders getNewFolder(Folders folder){
		String oldFolderName = folder.getFolderName();
		String newFolderName = oldFolderName;
		int rowCount = foldersMapper.selectFolderCount(folder);
		int count = 0;
		while(rowCount > 0){
			rowCount = foldersMapper.selectFolderCount(folder);
			if(rowCount > 0){
				count += 1;
				newFolderName = oldFolderName + " (" + count + ")";
				folder.setFolderName(newFolderName);
			}else {
				rowCount = -1;
			}
		}
		return folder;
	}
	
	//递归算法算出子节点
	private Set<Folders> findChildFolders(Set<Folders> foldersSet,Integer folderId,User user){
		Folders folders = foldersMapper.selectByPrimaryKey(folderId);
		if(folders != null){
			foldersSet.add(folders);
		}
		List<Folders> foldersList = foldersMapper.selectFolderChildrenByParentId(folderId,user.getUsername());
		for(Folders folderItem : foldersList){
			findChildFolders(foldersSet, folderItem.getFolderid(),user);
		}
		return foldersSet;
	}
	
	//递归批量插入
	private boolean recursiveInsert(List<Folders> foldersList,User user){
		boolean flag = false;
		int resultCount = foldersMapper.plInsert(foldersList);
		List<Folders> folders = Lists.newArrayList();
		List<Files> files = Lists.newArrayList();
		if(resultCount > 0){
			for(Folders foldersItem : foldersList){
				int folderId = foldersMapper.selectFolderIdByParentIdAndFolderName(foldersItem.getParentid(), foldersItem.getFolderName());
				List<Folders> list = foldersMapper.selectFolderByParentId(foldersItem.getFolderid());
				for(Folders Items : list){
					Items.setParentid(folderId);
					Items.setFolderName(getNewFolder(Items).getFolderName());
					Items.setUsername(user.getUsername());
					folders.add(Items);
				}
				List<Files> filesList = filesMapper.selectByFolderId(foldersItem.getFolderid());
				for(Files Items : filesList){
					Items.setFileid(IDUtil.getItemId());
					Items.setFolderId(folderId);
					Items.setFileRealName(fileUploadService.setNewFileName(Items));
					Items.setUsername(user.getUsername());
					files.add(Items);
				}
			}
			if(CollectionUtils.isEmpty(files)){flag = true;}
			else{
				resultCount = filesMapper.plInsert(files);
				if(resultCount > 0){
					flag = true;
				}
			}
		}
		if(CollectionUtils.isNotEmpty(folders)){
			recursiveInsert(folders,user);
		}
		return flag;
	}
	
	public ServerResponse getParentId(int folderid){
		int parentid = foldersMapper.selectParentIdByFolderId(folderid);
		
		
		Folders folders = foldersMapper.selectByPrimaryKey(parentid);
		
		if(folders.getParentid() == 0){
			folders.setFolderid(0);
		}
		
		return ServerResponse.createBySuccess("查询成功", folders);
	}
	
	private DirectoryVo assembleDirectoryVo(Folders folders,User user){
		DirectoryVo directoryVo = new DirectoryVo();
		directoryVo.setFolderid(folders.getFolderid());
		
		if(folders.getParentid() == 0){
			directoryVo.setName("全部文件");
		}else{
			directoryVo.setName(folders.getFolderName());
		}
		
		directoryVo.setParentid(folders.getParentid());
		
		ServerResponse<List<Integer>> responseServer = this.selectFoldersAndChildrenById(folders.getFolderid(),user);
		if(responseServer.isSuccess()){
			if(responseServer.getData().size() > 1){
				directoryVo.setIsParent(1);
			}
		}
		
		return directoryVo;
	}

}
